#!/usr/bin/env python3
"""
MySQL到KWDB迁移工具基本使用示例

本示例展示如何使用Python API进行数据迁移。
"""

import os
import sys
import logging

# 添加src目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))

from parser import MySQLParser
from converter import MySQLToKWDBConverter
from generator import KWDBSQLGenerator
from validator import MigrationValidator


def basic_migration_example():
    """基本迁移示例"""
    print("=== MySQL到KWDB迁移工具基本使用示例 ===\n")
    
    # 配置日志
    logging.basicConfig(level=logging.INFO)
    
    # 输入和输出文件
    input_file = "../tests/sample_data/mysql_dump.sql"
    output_file = "kwdb_output.sql"
    
    try:
        # 1. 解析MySQL SQL文件
        print("1. 解析MySQL SQL文件...")
        parser = MySQLParser()
        original_statements = parser.parse_file(input_file)
        
        print(f"   成功解析{len(original_statements)}个语句")
        
        # 显示解析结果统计
        type_counts = {}
        for stmt in original_statements:
            stmt_type = stmt.statement_type.value
            type_counts[stmt_type] = type_counts.get(stmt_type, 0) + 1
        
        print("   语句类型统计:")
        for stmt_type, count in type_counts.items():
            print(f"     {stmt_type}: {count}")
        
        # 2. 转换语法
        print("\n2. 转换MySQL语法到KWDB...")
        converter = MySQLToKWDBConverter()
        converted_statements = converter.convert_statements(original_statements)
        
        print(f"   成功转换{len(converted_statements)}个语句")
        
        # 获取转换摘要
        summary = converter.get_conversion_summary(original_statements, converted_statements)
        print(f"   转换成功率: {summary['total_converted']}/{summary['total_original']} "
              f"({summary['total_converted']/summary['total_original']*100:.1f}%)")
        
        # 3. 生成KWDB SQL文件
        print("\n3. 生成KWDB兼容SQL文件...")
        generator = KWDBSQLGenerator()
        success = generator.generate_sql_file(converted_statements, output_file)
        
        if success:
            print(f"   成功生成SQL文件: {output_file}")
        else:
            print("   生成SQL文件失败")
            return
        
        # 4. 验证迁移结果
        print("\n4. 验证迁移结果...")
        validator = MigrationValidator()
        validation_results = validator.validate_migration(
            original_statements, converted_statements
        )
        
        passed_count = len([r for r in validation_results if r.is_valid])
        total_count = len(validation_results)
        
        print(f"   验证完成: {passed_count}/{total_count} 项通过")
        
        # 显示验证结果
        for i, result in enumerate(validation_results, 1):
            status = "✅" if result.is_valid else "❌"
            print(f"     {i}. {status} {result.message}")
        
        # 5. 生成报告
        print("\n5. 生成迁移报告...")
        
        # 生成迁移报告
        migration_report = output_file.replace('.sql', '_migration_report.md')
        generator.generate_migration_report(
            original_statements, converted_statements, migration_report
        )
        print(f"   迁移报告: {migration_report}")
        
        # 生成验证报告
        validation_report = output_file.replace('.sql', '_validation_report.md')
        validator.generate_validation_report(validation_results, validation_report)
        print(f"   验证报告: {validation_report}")
        
        # 生成回滚脚本
        rollback_script = output_file.replace('.sql', '_rollback.sql')
        generator.generate_rollback_script(converted_statements, rollback_script)
        print(f"   回滚脚本: {rollback_script}")
        
        print("\n=== 迁移完成 ===")
        print(f"生成的文件:")
        print(f"  - KWDB SQL文件: {output_file}")
        print(f"  - 迁移报告: {migration_report}")
        print(f"  - 验证报告: {validation_report}")
        print(f"  - 回滚脚本: {rollback_script}")
        
    except Exception as e:
        print(f"迁移过程中出错: {e}")
        import traceback
        traceback.print_exc()


def custom_config_example():
    """自定义配置示例"""
    print("\n=== 自定义配置示例 ===\n")
    
    # 自定义配置
    custom_config = {
        'type_mapping': {
            'LONGTEXT': 'STRING',
            'MEDIUMTEXT': 'STRING',
            'TINYTEXT': 'STRING',
            'ENUM': 'STRING',
            'SET': 'STRING'
        },
        'syntax_rules': {
            'AUTO_INCREMENT': 'DEFAULT unique_rowid()',
            'ENGINE=MyISAM': '',
            'ENGINE=InnoDB': '',
            'DEFAULT CHARSET=utf8mb4': '',
            'COLLATE=utf8mb4_unicode_ci': ''
        }
    }
    
    # 使用自定义配置创建转换器
    converter = MySQLToKWDBConverter(custom_config)
    
    # 测试转换
    test_sql = """
    CREATE TABLE `test_table` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `content` LONGTEXT,
        `status` ENUM('active', 'inactive') DEFAULT 'active',
        PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
    """
    
    print("原始SQL:")
    print(test_sql)
    
    # 应用转换规则
    converted_sql = converter._apply_syntax_rules(test_sql)
    converted_sql = converter._convert_data_types(converted_sql)
    
    print("\n转换后的SQL:")
    print(converted_sql)


def validation_example():
    """验证功能示例"""
    print("\n=== 验证功能示例 ===\n")
    
    # 模拟表行数统计
    source_tables = {
        'users': 1000,
        'orders': 5000,
        'products': 200
    }
    
    target_tables = {
        'users': 1000,
        'orders': 4999,  # 故意设置不匹配
        'products': 200,
        'categories': 50  # 额外的表
    }
    
    validator = MigrationValidator()
    result = validator.validate_table_counts(source_tables, target_tables)
    
    print(f"验证结果: {'通过' if result.is_valid else '失败'}")
    print(f"消息: {result.message}")
    
    if result.details:
        print("详细信息:")
        for key, value in result.details.items():
            print(f"  {key}: {value}")


if __name__ == '__main__':
    # 运行基本迁移示例
    basic_migration_example()
    
    # 运行自定义配置示例
    custom_config_example()
    
    # 运行验证示例
    validation_example()
